//
//  CoolPickerViewController.m
//  CoolFramework
//
//  Created by Felix on 13-3-21.
//  Copyright (c) 2013年 FelixApp. All rights reserved.
//

#import "CoolPickerViewController.h"

@interface CoolPickerViewController () {
    NSArray *sectionedOptions_;
    NSArray *sectionedTitleKeys_;
    NSArray *sectionedValueKeys_;
    NSArray *sectionedSelectedIndexes_;
    void (^doneBlock_)(NSArray *sectionedSelections);
    void (^cancelBlock_)();
}

@property (nonatomic, weak) IBOutlet UIPickerView   *picker;
@property (nonatomic, weak) IBOutlet UIView         *blankView;

@end

@implementation CoolPickerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapViewGesture:)];
    [self.blankView addGestureRecognizer:tapGesture];
    
    if ([sectionedSelectedIndexes_ count] > 0) {
        [sectionedSelectedIndexes_ enumerateObjectsUsingBlock:^(NSNumber *selectedRow, NSUInteger idx, BOOL *stop) {
            if (![selectedRow isKindOfClass:[NSNumber class]]) {
                LogError(@"selectedRow is not a NSNumber object");
                return;
            }
            [self.picker selectRow:[selectedRow integerValue] inComponent:idx animated:NO];
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)selectionWithSectionedOptions:(NSArray*)sectionedOptions sectionedTitleKeys:(NSArray*)sectionedTitleKeys sectionedValueKeys:(NSArray*)sectionedValueKeys sectionedSelectedIndexes:(NSArray*)sectionedSelectedIndexes doneBlock:(void (^)(NSArray *sectionedSelections))doneBlock cancelBlock:(void (^)())cancelBlock {
    if (!sectionedOptions || sectionedOptions.count == 0 || (sectionedOptions.count != sectionedTitleKeys.count && sectionedOptions.count != sectionedValueKeys.count)) {
        LogError(@"invalid parameters!");
        return;
    }
    sectionedOptions_ = sectionedOptions;
    sectionedTitleKeys_ = sectionedTitleKeys;
    sectionedValueKeys_ = sectionedValueKeys;
    sectionedSelectedIndexes_ = sectionedSelectedIndexes;
    doneBlock_ = doneBlock;
    cancelBlock_ = cancelBlock;
}

- (IBAction)tapDoneButton:(id)sender {
    if (doneBlock_) {
        if (sectionedOptions_.count == 0) {
            doneBlock_(nil);
            return;
        }
        NSMutableArray *sectionedSelections = [NSMutableArray arrayWithCapacity:sectionedOptions_.count];
        [sectionedOptions_ enumerateObjectsUsingBlock:^(NSArray *rowArray, NSUInteger component, BOOL *stop) {
            if (![rowArray isKindOfClass:[NSArray class]]) {
                LogError(@"rowArray is not a NSArray object, but it is %@", rowArray);
                return;
            }
            NSDictionary *dict = rowArray[[self.picker selectedRowInComponent:component]];
            if (![dict isKindOfClass:[NSDictionary class]]) {
                LogError(@"dict is not a NSDictionary object, but it is %@", dict);
                return;
            }
            id titleKey = sectionedTitleKeys_[component];
            id title = dict[titleKey];
            if (!title) {
                title = @"";
            }
            id valueKey = sectionedValueKeys_[component];
            id value = dict[valueKey];
            if (!value) {
                value = @"";
            }
            NSDictionary *selection = @{@"title": title, @"value": value};
            [sectionedSelections addObject:selection];
        }];
        doneBlock_(sectionedSelections);
    }
}

- (IBAction)tapCancelButton:(id)sender {
    if (cancelBlock_) {
        cancelBlock_();
    }
}

- (void)handleTapViewGesture:(UIGestureRecognizer*)gesture {
    if (gesture.state != UIGestureRecognizerStateRecognized) {
        return;
    }
    if (cancelBlock_) {
        cancelBlock_();
    }
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return sectionedOptions_.count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSArray *rowArray = sectionedOptions_[component];
    if (![rowArray isKindOfClass:[NSArray class]]) {
        LogError(@"rowArray is not a NSArray object, but it is %@", rowArray);
        return 0;
    }
    return rowArray.count;
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSArray *rowArray = sectionedOptions_[component];
    NSDictionary *dict = rowArray[row];
    if (![dict isKindOfClass:[NSDictionary class]]) {
        LogError(@"dict is not a NSDictionary object, but it is %@", dict);
        return @"";
    }
    id titleKey = sectionedTitleKeys_[component];
    return dict[titleKey];
}

//#pragma mark - UIGestureRecognizerDelegate
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
//{
//    if (gestureRecognizer.view == otherGestureRecognizer.view) {
//        return YES;
//    } else {
//        return NO;
//    }
//}
@end
